<?php
class UserController extends Ovis_Controller
{
	public function init()
	{		
		$actionName = $this->getRequest()->getActionName();
		if (in_array($actionName, array('login', 'login-submit'))) {
			$this->requiredLoggedIn = false;
		}
		parent::init();

	}

	/**
	* Login action - show the login form
	*/
	public function loginAction()
	{
		$this->_helper->getHelper('layout')->disableLayout();
	}

	/**
	* Process for login action
	* @throws Sss_Exceptions_Abstract
	*/
	public function loginSubmitAction()
	{
		$username = $this->getRequest()->getParam('username',"");
		$password = $this->getRequest()->getParam('password',"");
		$userAuthAdapter = new Ovis_Auth_UserAdapter(array(
		'username' => $username,
		'password'=> $password
		));
		$instanceTable     = new Application_Model_Mapper_Instance();
		$accountTable      = new Application_Model_Mapper_Account();
		$accountTable->checkEsixtedColumns('otrs_user_id');
		$instanceTable->checkEsixtedColumns('otrs_group');
		// Authentication with POST params
		$result = Zend_Auth::getInstance()->authenticate($userAuthAdapter);
		if ($result->isValid()) {
			$encryptedPassword = Sss_Crypt::factory()->encrypt($password);
			$ot = new Sss_Ultility_OtrsServices();
			if (is_null($result->getIdentity()->otrs_user_id) && $result->getIdentity()->accounttype != Sss_Ultility_Setting::ACCOUNT_VENDOR) {
				$arrParams = array();
				$arrParams['fullname'] =  $result->getIdentity()->fullName;
				$arrParams['username'] =  $username . $result->getIdentity()->accountid;
				$arrParams['password'] =  $encryptedPassword;
				$arrParams['role'] =  0;
				$arrParams['email'] =  $result->getIdentity()->accountid.$result->getIdentity()->email;
				$arrParams['wsuser'] =  USER_SERVICE;
				$arrParams['wspass'] =  PASSWORD_SERVICE;
				$userOtrsId   = $ot->createUser(USER_SERVICE_ID, 1, $arrParams);
				if(is_null($userOtrsId)) {
					$this->redirect(Resources::_('USER_NAME_EXIST'), $this->view->url(array(
					Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
					Sss_Ultility_CommonViewParamater::ACTION => $this->view->actionName
					)));
				}
				$accountUpdate = $accountTable->findById($result->getIdentity()->accountid);
				$accountUpdate->setOtrsUserId($userOtrsId);
				$accountTable->save($accountUpdate);
				if($type == Sss_Ultility_Setting::ACCOUNT_OVIS) {
					$instances = $instanceTable->getConectedInstanceList();
					foreach($instances as $instance){
						if(!is_null($instance['otrs_group'])) {
							assignUser2Group(USER_SERVICE_ID,$userOtrsId, null, $instance['otrs_group'], USER_SERVICE, PASSWORD_SERVICE);
						}
					}
				}
			}
			//Create session with url auto login OTRS
			$sessionAutoLoginUrl = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_AUTO_LOGIN_SESSION);
			$autoLogin =   $ot->autoLogin(USER_SERVICE_ID ,null,$username . $result->getIdentity()->accountid,$encryptedPassword, "BO", USER_SERVICE, PASSWORD_SERVICE);
			$sessionAutoLoginUrl->autourl = $autoLogin;
			// Redirect to admin homepage
			$this->_redirect('/');
		} else {
			if($username == "" || $password == "") {
				// Return when not input username or password
				$this->view->message = Resources::_('INVALID_INPUT');
				$this->_forward(Sss_Ultility_CommonViewParamater::LOGIN);
			} else {
				// Return the login page
				$this->view->message = Resources::_('INVALID_USERNAME_PASSWORD');
				$this->_forward(Sss_Ultility_CommonViewParamater::LOGIN);
			}
		}
	}

	public function logoutAction() 
	{
		Zend_Auth::getInstance()->clearIdentity();
		$autoLogin = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_AUTO_LOGIN_SESSION);
		$autoLogin->setExpirationSeconds(Sss_Ultility_Setting::EXPIRATION);
		$this->getValueRequest(Sss_Ultility_SessionName::OVIS_AUTO_LOGIN_SESSION, null);
		$this->_redirect('/');
	}
	public function forgotPasswordAction()
	{
		$this->_helper->getHelper('layout')->disableLayout();
	}
	public function forgotPasswordSubmitAction()
	{
		//get params
		$params = $this->getRequest()->getPost();
		if((!isset($params['username']) && !isset($params['email'])) || ($params['username'] == '' && $params['email'] == '')) {
			$this->view->message = Resources::_('INVALID_INPUT');
			$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
		}
		//send mail to user with information active code
		$accountTable = new Application_Model_Mapper_Account();
		$account = null;
		try {
			$email = null;
			if(isset($params['email']) && $params['email'] != '') {
				$account = $accountTable->getUserByEmail($params['email']);
				if($account != false){
					$email = $account->email;
				}
			}
			elseif(isset($params['username']) && $params['username'] != '') {
				$account = $accountTable->getUser($params['username']);
				if($account != false){
					$email = $account->email;
				}
			} else {
				$this->view->message = Resources::_('INVALID_INPUT');
				$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
				return;
			}
			if($email == null) {
				$this->view->message = Resources::_('INVALID_USERNAME_EMAIL');
				$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
				return; 
			}

			$activateCode   = Sss_Ultility_Common::genRandomString(75);
			$getAccountId = $accountTable->getUserByEmail($email);
			$accountUpdate = $accountTable->findById($getAccountId->accountid);
			$accountUpdate->setActivateCode($activateCode);
			$accountUpdate->setIsActivated(0);
			$accountTable->save($accountUpdate);
			$subject = Resources::_('OVIS_SUBJECT_FORGOT_PASSWORD');
			$body    = Resources::_('BODY1'). " \n \n"
			.Resources::_('BODY2').' '.DOMAIN_SYSTEM."/active/active?activatecode=$activateCode&popup=1&forgotpassword=1". " \n \n"
			.Resources::_('BODY4'). " \n \n"
			.Resources::_('BODY5'). " \n \n"
			.Resources::_('BODY6');

			Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $email, $subject, $body);
			$this->view->message = Resources::_('RETRIEVE_PASSWORD_SUCCESSFULL');
			$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
		} catch (Exception $e) {
			Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
			$this->view->message = Resources::_('RETRIEVE_PASSWORD_FAIL');
			$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
		}
	}
	public function changePasswordAction()
	{
		$this->checkInstance();
		$userInformation = Ovis_Controller::getLoggedUser();
		$this->view->assign(Sss_Ultility_CommonViewParamater::FULLNAME, $userInformation['fullname']);
		$accountTable     = new Application_Model_Mapper_Account();

		//get params
		$params = $this->getRequest()->getPost();
		if($userInformation && isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
			//check username and password
			$account = $accountTable->getUser($userInformation['username']);
			if($account != false)
				$account = (array)$account;
			$crypt = Sss_Crypt::factory();
			$encryptedPassword = $crypt->encrypt($params['currentpassword']);
			if($account != false && $encryptedPassword == $account['password']){

				//check confirm new password
				if(trim($params['password']) == trim($params['confirmnewpassword'])) {
					try {
						$encryptedNewPassword = Sss_Crypt::factory()->encrypt($params['password']);
						$accountUpdate = $accountTable->findById($account['accountid']);
						$accountUpdate->setPassword($encryptedNewPassword);
						$accountTable->save($accountUpdate);

						//Delete user in OTRS service when delete user in ovis site
						$otrs = new Sss_Ultility_OtrsServices();
						$fullName = $account['fullname'];
						$userName = $account['username'];
						$email = $account['email'];
						$otrs->updateUser($account['otrs_user_id'], USER_SERVICE_ID, 1, $fullName, $userName.$account['accountid'], $email, $encryptedNewPassword, USER_SERVICE, PASSWORD_SERVICE);

						$this->view->message = Resources::_('CHANGE_PASSWORD_SUCCESSFULL');
						$this->_forward(Sss_Ultility_CommonViewParamater::LOGIN);
					} catch (Exception $e) {
						Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
						$this->view->message = Resources::_('CHANGE_PASSWORD_FAIL');
						$this->_forward(Sss_Ultility_CommonViewParamater::CHANGE_PASSWORD);
					}
				} else {
					$this->view->message = Resources::_('CONFIRM_NEW_PASSWORD_FAIL');
					$this->_forward(Sss_Ultility_CommonViewParamater::CHANGE_PASSWORD);
				}
			}
		}
	}
}
